package com.topit.show.aliapi;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.bike.entity.HhOpenUser;
import com.bike.entity.HhOrder;
import com.bike.util.Constant;
import com.bike.util.PageData;
import com.topit.show.wxapi.common.WxConstants;

public class AliUtil {
	
	
	
	
	//获取ali用户id
	public static String getAliOpenid(String aliCode, String businessId)  {
		String openid =null;
		if (StringUtils.isNotEmpty(aliCode)) {
			String charset= "UTF-8";
			AlipayClient alipayClient = new DefaultAlipayClient(AliConstant.gateway, AliConstant.appId, AliConstant.aliPrivateKey, "json", charset, AliConstant.aliPublicKey, "RSA2"); 
			AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
			request.setCode(aliCode);
			request.setGrantType("authorization_code");
			try {
			    AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
			    openid= oauthTokenResponse.getUserId();
			} catch (AlipayApiException e) {
			    e.printStackTrace();
			} 
		}
		return openid;
	}

	public static String getPayForm(HhOpenUser user, PageData pd, HhOrder order) {
		 
		 
		AlipayClient alipayClient = new DefaultAlipayClient(AliConstant.gateway, AliConstant.appId, AliConstant.aliPrivateKey, "json",AliConstant.CHARSET, AliConstant.aliPublicKey, AliConstant.SIGN_TYPE); //获得初始化的AlipayClient
		AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
		alipayRequest.setReturnUrl(AliConstant.returnUrl.concat(order.getOrderId().toString()));
		alipayRequest.setNotifyUrl(AliConstant.notifyUrl);//在公共参数中设置回跳和通知地址
		
		JSONObject bizContent=new JSONObject();
		bizContent.put("out_trade_no", order.getOrderId());
		bizContent.put("total_amount", order.getTotalPrice().doubleValue());
		bizContent.put("subject", "下单");
		bizContent.put("product_code", "QUICK_WAP_PAY");
		
		alipayRequest.setBizContent(bizContent.toJSONString()); //填充业务参数
		String form="";
		try {
		form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
		} catch (AlipayApiException e) {
		e.printStackTrace();
		}
		return form;
	}

	public static String getRedirectUrl(String url,Long businessId) {
		String appId=AliConstant.appId;
		url=WxConstants.SERVER_BASE_PATH.concat(url);
		return AliConstant.ALI_OAUTH_URL.concat("?scope=auth_base&app_id=").concat(appId).concat("&redirect_uri=").concat(url).concat("&state=").concat(businessId.toString());
	}
}
